package com.lanou3g.ssm.interceptor;

import com.lanou3g.ssm.bean.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 该拦截器检查用户登录状态，如果失效，则重定向到登录页，让用户重新登录
 */
public class SessionInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		HttpSession session = request.getSession();
		User loginUser = (User) session.getAttribute("userInfo");
		if(loginUser == null) {
			try {
				response.setContentType("text/html");
				response.getWriter().println("<script>alert('登录过期，请重新登录!');window.location.href = '/login';</script>");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return false;
		}
		return true;
	}
}
